import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import Loading from 'widget/Loading';
import CommentService from 'service/RequestServices/CommentService';
import PopupCard from './PopupCard';
import TextCard from './TextCard';

const Container = styled.div`
  margin-bottom: 12px;
`;

class CommentCard extends PureComponent {
  state = {
    loading: false,
    content: '',
    commented: false
  };

  handleSubmit = content => {
    let { loading } = this.state;
    loading = true;
    this.setState(
      {
        loading
      },
      () => {
        this.comment(content);
      }
    );
  };

  comment = content => {
    const { answerID } = this.props;
    let { loading, commented } = this.state;
    loading = true;

    CommentService.postComment({
      answerID,
      content,
      type: 0
    }).then(() => {
      loading = false;
      commented = true;
      this.setState({
        loading,
        commented,
        content
      });
    });
  };

  render() {
    const { loading, commented } = this.state;

    if (loading) {
      return <Loading />;
    }

    if (commented) {
      return (
        <Container>
          <PopupCard>{this.state.content}</PopupCard>
        </Container>
      );
    }

    return (
      <FormattedMessage id="post.comment.placeholder">
        {([txt]) => {
          return (
            <TextCard
              autofocus
              {...this.props}
              placeholder={txt}
              onSubmit={content => this.handleSubmit(content)}
            />
          );
        }}
      </FormattedMessage>
    );
  }
}

CommentCard.propTypes = {
  answerID: PropTypes.number.isRequired
};

export default CommentCard;
